package com.wey.service;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.util.EntityUtils;

public class GradioClient {
    private static final String BASE_URL = "https://ai-modelscope-deepseek-playground.ms.show/";
    private static final String token = "143ffe9f-009f-40fa-a2b1-e8591a0a64de";

    // 提交聊天请求
    public static String[] submitChat(String model, String input) throws Exception {
        HttpPost post = new HttpPost(BASE_URL + "run/submit_chat");
//        post.setHeader("Authorization", "Bearer " + token);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .addTextBody("data", String.format("[[\"%s\", \"%s\"], null]", model, input))
            .addTextBody("fn_index", "0");  // 需要根据实际API调整

        return executeRequest(post, builder);
    }

    // 重载方法使用默认模型
    public static String[] submitChat(String input) throws Exception {
        return submitChat("deepseek-ai/DeepSeek-R1", input);
    }

    // 取消提交
    public static String[] cancelSubmit() throws Exception {
        HttpPost post = new HttpPost(BASE_URL + "run/cancel_submit");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .addTextBody("fn_index", "1");  // 需要根据实际API调整

        return executeRequest(post, builder);
    }

    // 清除聊天
    public static String[] clearChat() throws Exception {
        HttpPost post = new HttpPost(BASE_URL + "run/clear_chat");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .addTextBody("fn_index", "2");  // 需要根据实际API调整

        return executeRequest(post, builder);
    }

    private static String[] executeRequest(HttpPost post, MultipartEntityBuilder builder) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(post)) {
            
            post.setEntity(builder.build());
            HttpEntity responseEntity = response.getEntity();
            String responseString = EntityUtils.toString(responseEntity);
            
            // 这里需要根据实际响应格式解析
            return parseResponse(responseString);
        }
    }

    private static String[] parseResponse(String response) {
        // 示例解析逻辑（实际需要根据API返回格式调整）
        return response.replaceAll("[\\[\\]\"]", "").split(",");
    }

    public static void main(String[] args) throws Exception {
        // 使用示例
        String[] chatResult = submitChat("Hello");
        System.out.println("Response: " + String.join(", ", chatResult));
    }

//    public static void main(String[] args) {
//        try {
//            // 1. 登录认证
//            String token = ModelScopeAuth.authenticate("your_username", "your_password");
//
//            // 2. 创建API请求
//            HttpPost chatRequest = new HttpPost("https://api.modelscope.cn/v1/chat");
//            chatRequest.setHeader("Authorization", "Bearer " + token);
//
//            // 3. 设置请求参数
//            String requestBody = "{\"model\":\"deepseek-chat\",\"messages\":[{\"role\":\"user\",\"content\":\"Hello\"}]}";
//            chatRequest.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
//
//            // 4. 执行请求并处理响应
//            try (CloseableHttpClient client = HttpClients.createDefault();
//                 CloseableHttpResponse response = client.execute(chatRequest)) {
//
//                ChatCompletionResponse resp = parseResponse(response);
//                System.out.println(resp.getChoices().get(0).getMessage().getContent());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}